package com.itheima.project.service.impl;

import com.alibaba.fastjson.JSON;
import com.itheima.project.anno.EsId;
import com.itheima.project.anno.EsIndex;
import com.itheima.project.core.enums.search.SearchEnum;
import com.itheima.project.exception.ProjectException;
import com.itheima.project.service.DocumentService;
import com.itheima.project.vo.search.SearchPageVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;

/**
 * @author mrchen
 * @date 2022/3/8 16:34
 */
@Service
@Slf4j
public class DocumentServiceImpl implements DocumentService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public <T> void save(T doc) throws ProjectException {
//        save(doc,getIndexName(doc.getClass()));
    }

    @Override
    public void save(Map doc, String indexName) throws ProjectException {
        log.debug("集合名称: {}  文档数据 : {}", indexName, doc);
        try {
            // 1.创建Request对象
            IndexRequest request = new IndexRequest(indexName);
            // 2.准备参数，id和文档数据
            request.id(getId(doc));
            request.source(JSON.toJSONString(doc), XContentType.JSON);
            // 3.发出请求
            client.index(request, RequestOptions.DEFAULT);
            log.debug("添加文档成功");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("添加文档失败， 原因: {}", e.getMessage());
            throw new ProjectException(SearchEnum.DOCUMENT_CREATE_FAIL);
        }
    }

    @Override
    public void saveBatch(List<Map> list,String indexName) throws ProjectException {
        try {
            // 1.创建Request对象
            BulkRequest request = new BulkRequest(indexName);
            // 2.准备参数
            for (Map t : list) {
                request.add(new IndexRequest().id(getId(t)).source(JSON.toJSONString(t), XContentType.JSON));
            }
            // 3.发出请求
            client.bulk(request, RequestOptions.DEFAULT);
            log.debug("批量添加文档成功");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("添加文档失败， 原因: {}", e.getMessage());
            throw new ProjectException(SearchEnum.DOCUMENT_CREATE_FAIL);
        }
    }
    @Override
    public void deleteById(Object id, String indexName) {
        try {
            // 1.请求
            DeleteRequest request = new DeleteRequest(indexName, String.valueOf(id));
            // 2.发出请求
            client.delete(request, RequestOptions.DEFAULT);
            log.debug("删除文档成功");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("删除文档失败， 原因: {}", e.getMessage());
            throw new ProjectException(SearchEnum.DOCUMENT_DELETE_FAIL);
        }
    }

    @Override
    public <T> T getById(Object id, Class<T> tClass) {
        try {
            // 1.请求
            GetRequest request = new GetRequest(getIndexName(tClass), String.valueOf(id));
            // 2.发出请求
            GetResponse response = client.get(request, RequestOptions.DEFAULT);
            // 3.解析结果
            String json = response.getSourceAsString();
            // 4.反序列化
            return JSON.parseObject(json, tClass);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("查询文档失败， 原因: {}", e.getMessage());
            throw new ProjectException(SearchEnum.DOCUMENT_SEARCH_FAIL);
        }
    }

    @Override
    public Object getById(Object id, String indexName) {
        try {
            // 1.请求
            GetRequest request = new GetRequest(indexName, String.valueOf(id));
            // 2.发出请求
            GetResponse response = client.get(request, RequestOptions.DEFAULT);
            // 3.解析结果
            String json = response.getSourceAsString();
            // 4.反序列化
            return JSON.parseObject(json);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("查询文档失败， 原因: {}", e.getMessage());
            throw new ProjectException(SearchEnum.DOCUMENT_SEARCH_FAIL);
        }
    }

    @Override
    public SearchResponse search(SearchSourceBuilder sourceBuilder, Class<?> tClass) {
        try {
            // 1.准备request
            SearchRequest request = new SearchRequest(getIndexName(tClass));
            // 2.准备参数
            request.source(sourceBuilder);
            // 3.发出请求
            return client.search(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ProjectException(SearchEnum.DOCUMENT_SEARCH_FAIL);
        }
    }

    @Override
    public SearchResponse search(SearchSourceBuilder sourceBuilder, String indexName) {
        try {
            // 1.准备request
            SearchRequest request = new SearchRequest(indexName);
            // 2.准备参数
            request.source(sourceBuilder);
            // 3.发出请求
            return client.search(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ProjectException(SearchEnum.DOCUMENT_SEARCH_FAIL);
        }
    }

    @Override
    public <T> SearchPageVo<T> page(SearchSourceBuilder sourceBuilder, Class<T> tClass) {
        SearchResponse response = search(sourceBuilder, tClass);
        // 4.解析结果
        SearchHits searchHits = response.getHits();
        // 4.1.获取总条数
        long total = searchHits.getTotalHits().value;
        // 4.2.获取数据
        SearchHit[] hits = searchHits.getHits();
        SearchPageVo<T> pageVo = new SearchPageVo<>();
        List<T> list = new ArrayList<>(hits.length);
        // 4.3.循环处理
        for (SearchHit hit : hits) {
            // 获取source
            String json = hit.getSourceAsString();
            // 反序列化
            T t = JSON.parseObject(json, tClass);
            list.add(t);
            // 高亮处理
            handleHighlight(t, hit);
        }
        pageVo.setTotal(total);
        pageVo.setRecords(list);
        return pageVo;
    }

    private void handleHighlight(Object t, SearchHit hit) {
        try {
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            for (HighlightField highlightField : highlightFields.values()) {
                // 获取高亮字段名称
                String fieldName = highlightField.getName();
                // 获取高亮结果
                String highlightValue = StringUtils.join(highlightField.getFragments());
                // 获取字节码
                BeanUtils.setProperty(t, fieldName, highlightValue);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("工具类: 反射解析处理高亮结果失败");
            throw new ProjectException(SearchEnum.DOCUMENT_SEARCH_FAIL);
        }
    }
    private String getId(Map map) {
        Object id = map.get("id");
        if (id == null) {
            String uuid = UUID.randomUUID().toString();
            log.warn("未发现id属性，自动生成文档id ==> {}",uuid);
            return uuid;
        }
        return id.toString();
    }

    /**
     * 反射 基于id注解  获取id值
     * @param t
     * @return
     */
    private String getId(Object t) {
        try {
            Class<?> tClass = t.getClass();
            Field[] declaredFields = tClass.getDeclaredFields();
            Object id = null;
            for (Field declaredField : declaredFields) {
                declaredField.setAccessible(true);
                String name = declaredField.getName();
                if (declaredField.isAnnotationPresent(EsId.class) || "id".equals(name)) {
                    id = declaredField.get(t);
                }
            }
            if (id == null) {
                log.error("es工具类出错， 未发现标记@EsId注解 id解析失败");
                throw new ProjectException(SearchEnum.DOCUMENT_CREATE_FAIL);
            }
            return id.toString();
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    private String getIndexName(Class<?> c) {
        EsIndex annotation = c.getAnnotation(EsIndex.class);
        if (annotation == null) {
            throw new ProjectException(SearchEnum.FAIL.getCode(), "获取索引库名称失败，未发现@EsIndex注解");
        }
        // 索引库名称
        return annotation.indexName();
    }
}
